import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
// @ts-ignore
import { ElMessage } from "element-plus";
import { ScrollPosition } from "../util/scrollTo";
import { nextTick, ref } from "vue";
import { throuttle } from "../util/utils"
const routes: Array<RouteRecordRaw> = [
    {
        path: "/",
        redirect: "/file/1",
    },
    {
        path: "/file/:id",
        name: "file",
        meta: {
            needLogin: true,
            needHeader: true,
        },
        component: () => import("@/views/fileOperate.vue"!),
    },
    {
        path: "/search",
        name: "search",
        meta: {
            needLogin: true,
            needHeader: true,
        },
        component: () => import("@/views/fileOperate.vue"!),
    },
    {
        path: "/longlist",
        name: "longlist",
        meta: {
            needLogin: false,
            needHeader: true,
        },
        component: () => import("@/views/longlist.vue"!),
    },
    {
        path: "/test",
        name: "test",
        meta: {
            needLogin: true,
            needHeader: true,
        },
        component: () => import("@/views/test.vue"!),
    },
    {
        path: "/video/:id",
        name: "video",
        meta: {
            needLogin: true,
            needHeader: true,
        },
        component: () => import("@/views/video.vue"),
    },
    {
        path: "/login",
        name: "login",
        meta: {
            needLogin: false,
            needHeader: false,
        },
        component: () => import("@/views/login.vue"),
    },
    {
        path: "/history",
        name: "history",
        meta: {
            needLogin: true,
            needHeader: true,
        },
        component: () => import("@/views/history.vue"),
    },
    {
        path: "/collect",
        name: "collect",
        meta: {
            needLogin: true,
            needHeader: true,
        },
        component: () => import("@/views/collect.vue"),
    },
    {
        path: "/favourite",
        name: "favourite",
        meta: {
            needLogin: true,
            needHeader: true,
        },
        component: () => import("@/views/favourite.vue"),
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes
});

interface PathScrollY {
    path: string;
    scrollY: number;
}
const pathScrollYArr: PathScrollY[] = [];
const maxCacheLength = 10;


export let position = ref(0)

const getPosition = throuttle( () => {
    position.value = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
}, 100)

window.addEventListener("scroll", getPosition);


function setPathScrollYArr(path: string) {
    let index = pathScrollYArr.findIndex((item) => path == item.path);
    if (index == -1) {
        // 不存在且数组中有10个历史，删除之前的历史
        if (pathScrollYArr.length >= maxCacheLength) {
            pathScrollYArr.shift();
        }
        pathScrollYArr.push({
            path,
            scrollY: position.value
        });
    } else {
        const item = pathScrollYArr.splice(index, 1)[0]; // 通过splice方法将指定项从数组中删除并返回
        item.scrollY = position.value
        pathScrollYArr.push(item); // 将该项添加到数组末尾
    }
}

router.beforeEach((to, from, next) => {
    if (to.path == "/login" && localStorage.getItem("token")) {
        next("/");
        return;
    }
    if (to.meta.needLogin && localStorage.getItem("token")) {
        setPathScrollYArr(from.path);
        next();
    } else if (to.meta.needLogin && !localStorage.getItem("token")) {
        if (to.path !== "/login") {
            ElMessage({
                type: "warning",
                message: "请重新登录",
            });
            next("/login");
        }
    } else {
        setPathScrollYArr(from.path);
        next();
    }
});


const scrollPosition = new ScrollPosition()

router.afterEach(async (to) => {
    // console.log(to.path);
    await nextTick();
    let index = pathScrollYArr.findIndex((item) => to.path == item.path);
    if (index === -1) {
        scrollPosition.smoothScrollTo(0, 0);
    } else {
        setTimeout(() => {
            scrollPosition.smoothScrollTo(pathScrollYArr[index].scrollY, 0);
        },0)
    }
});

export default router;

 
